<template>
  <MainLayout>
    <div class="home-page">
      <!-- 页面标题和操作按钮 -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">任务列表</h2>
        <n-button 
          type="primary" 
          @click="showCreateTaskDialog = true"
        >
          <template #icon>
            <n-icon size="18">
              <AddOutline />
            </n-icon>
          </template>
          添加任务
        </n-button>
      </div>
      
      <!-- 主内容区 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
        <!-- 左侧分组列表 -->
        <div class="md:col-span-1">
          <GroupList 
            :groups="groups" 
            :current-group-id="currentGroupId"
            @select="selectGroup"
          />
        </div>
        
        <!-- 右侧任务列表 -->
        <div class="md:col-span-3">
          <!-- 任务过滤和搜索 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-4">
            <div class="flex flex-wrap gap-4">
              <n-select 
                v-model:value="filter.status" 
                placeholder="任务状态"
                :options="statusOptions"
                class="w-32"
                @update:value="fetchTasks"
              >
                <template #prefix>
                  <n-icon size="18">
                    <FilterOutline />
                  </n-icon>
                </template>
              </n-select>
              
              <n-checkbox v-model:checked="filter.isImportant" @update:checked="fetchTasks">
                只看重要任务
              </n-checkbox>
              
              <div class="flex-1"></div>
              
              <n-input 
                v-model:value="searchKeyword" 
                placeholder="搜索任务..."
                @keyup.enter="fetchTasks"
                class="w-48"
              >
                <template #prefix>
                  <n-icon size="18">
                    <SearchOutline />
                  </n-icon>
                </template>
              </n-input>
            </div>
          </div>
          
          <!-- 任务列表 -->
          <div v-if="isLoading" class="flex justify-center items-center py-12">
            <n-spin size="large" />
          </div>
          
          <div v-else-if="currentGroupTasks.length === 0" class="text-center py-12">
            <n-empty description="暂无任务">
              <template #icon>
                <n-icon size="48">
                  <DocumentTextOutline />
                </n-icon>
              </template>
              <n-button type="primary" @click="showCreateTaskDialog = true">
                创建第一个任务
              </n-button>
            </n-empty>
          </div>
          
          <div v-else>
            <TaskCard 
              v-for="task in currentGroupTasks" 
              :key="task.task_id"
              :task="task"
            />
          </div>
          
          <!-- 分页 -->
          <n-pagination 
            v-if="total > pageSize"
            v-model:page="currentPage"
            :page-size="pageSize"
            :page-count="Math.ceil(total / pageSize)"
            @update:page="fetchTasks"
            class="mt-6 flex justify-center"
          />
        </div>
      </div>
      
      <!-- 创建任务对话框 -->
      <n-dialog v-model:show="showCreateTaskDialog" title="创建任务" width="600px">
        <n-form 
          :model="createTaskForm" 
          :rules="createTaskRules"
          ref="createTaskFormRef"
        >
          <n-form-item path="title">
            <n-input 
              v-model:value="createTaskForm.title" 
              placeholder="请输入任务标题"
              autofocus
            />
          </n-form-item>
          
          <n-form-item path="group_id">
            <n-select 
              v-model:value="createTaskForm.group_id" 
              placeholder="请选择任务分组"
              :options="groupOptions"
            >
              <template #prefix>
                <n-icon size="18">
                  <ListOutline />
                </n-icon>
              </template>
            </n-select>
          </n-form-item>
          
          <n-form-item path="description">
            <n-input
              v-model:value="createTaskForm.description"
              type="textarea"
              placeholder="请输入任务描述"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </n-form-item>
          
          <div class="grid grid-cols-2 gap-4">
            <n-form-item>
              <n-date-picker 
                v-model:value="createTaskForm.due_date" 
                type="date"
                placeholder="选择截止日期"
              />
            </n-form-item>
            
            <div class="flex items-center space-x-4">
              <n-checkbox v-model:checked="createTaskForm.is_important">重要任务</n-checkbox>
              <n-checkbox v-model:checked="createTaskForm.is_my_day">我的一天</n-checkbox>
            </div>
          </div>
        </n-form>
        <template #footer>
          <div class="flex justify-end space-x-2">
            <n-button @click="showCreateTaskDialog = false">取消</n-button>
            <n-button 
              type="primary" 
              @click="handleCreateTask"
              :loading="isCreating"
            >
              创建任务
            </n-button>
          </div>
        </template>
      </n-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import MainLayout from '@/layouts/MainLayout.vue'
import GroupList from '@/components/GroupList.vue'
import TaskCard from '@/components/TaskCard.vue'
import { useGroupStore } from '@/store/group'
import { useTaskStore } from '@/store/task'
import { CreateTaskRequest } from '@/types'
import { 
  AddOutline, 
  FilterOutline, 
  SearchOutline, 
  DocumentTextOutline,
  ListOutline
} from '@vicons/ionicons5'
import type { FormInstance } from 'naive-ui'

// 状态
const showCreateTaskDialog = ref<boolean>(false)
const createTaskFormRef = ref<FormInstance | null>(null)
const searchKeyword = ref<string>('')

// 过滤条件
const filter = reactive({
  status: undefined as number | undefined,
  isImportant: false
})

// 任务状态选项
const statusOptions = [
  { label: '全部', value: undefined },
  { label: '新任务', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 }
]

// 获取分组store
const groupStore = useGroupStore()

// 获取任务store
const taskStore = useTaskStore()

// 从store获取数据
const groups = computed(() => groupStore.groups)
const currentGroupId = computed(() => groupStore.currentGroupId)
const currentGroupTasks = computed(() => taskStore.tasks.filter(task => task.group_id === currentGroupId.value))
const isLoadingGroups = computed(() => groupStore.isLoading)
const isLoadingTasks = computed(() => taskStore.isLoading)
const isLoading = computed(() => isLoadingGroups.value || isLoadingTasks.value)

// 分页状态
const currentPage = computed(() => taskStore.currentPage)
const pageSize = computed(() => taskStore.pageSize)
const total = computed(() => taskStore.total)

// 使用taskStore的fetchTasks方法获取任务列表
const fetchTasks = async (params?: {
  group_id?: number
  status?: number
  is_important?: boolean
  page?: number
  page_size?: number
}) => {
  await taskStore.fetchTasks({
    group_id: params?.group_id || currentGroupId.value,
    status: params?.status || filter.status,
    is_important: params?.is_important || filter.isImportant,
    page: params?.page,
    page_size: params?.page_size
  })
}

// 分组选项（用于创建任务时选择分组）
const groupOptions = computed(() => {
  return groups.value.map(group => ({
    label: group.name,
    value: group.group_id
  }))
})

// 创建任务表单
const createTaskForm = reactive<CreateTaskRequest>({
  group_id: currentGroupId.value,
  title: '',
  description: '',
  is_important: false,
  is_my_day: false,
  due_date: undefined
})

// 创建任务表单规则
const createTaskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { min: 1, max: 100, message: '任务标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  group_id: [
    { required: true, message: '请选择任务分组', trigger: 'blur' }
  ]
}

// 使用useFetcher创建任务
const {
  loading: isCreating,
  send: createTask
} = useFetcher(createTaskApi)

// 监听当前分组ID变化，更新创建任务表单的分组ID
const updateCreateTaskGroupId = () => {
  createTaskForm.group_id = currentGroupId.value
}

// 选择分组
const selectGroup = (groupId: number) => {
  groupStore.setCurrentGroup(groupId)
  updateCreateTaskGroupId()
  fetchTasks()
}

// 处理创建任务
const handleCreateTask = async () => {
  if (!createTaskFormRef.value) return
  
  try {
    await createTaskFormRef.value.validate()
    await createTask(createTaskForm)
    showCreateTaskDialog.value = false
    // 重置表单
    resetCreateTaskForm()
    // 刷新任务列表
    fetchTasks({
      group_id: currentGroupId.value,
      status: filter.status,
      is_important: filter.isImportant,
      page: currentPage.value,
      page_size: pageSize.value
    })
  } catch (error) {
    console.error('创建任务失败:', error)
  }
}

// 重置创建任务表单
const resetCreateTaskForm = () => {
  createTaskForm.title = ''
  createTaskForm.description = ''
  createTaskForm.is_important = false
  createTaskForm.is_my_day = false
  createTaskForm.due_date = undefined
  createTaskForm.group_id = currentGroupId.value
  createTaskFormRef.value?.restoreValidation()
}

// 监听过滤条件变化，刷新任务列表
watch(filter, () => {
  fetchTasks({
    group_id: currentGroupId.value,
    status: filter.status,
    is_important: filter.isImportant,
    page: currentPage.value,
    page_size: pageSize.value
  })
}, { deep: true })

// 页面加载时获取数据
onMounted(async () => {
  // 获取分组列表
  await groupStore.fetchGroups()
  // 更新创建任务表单的分组ID
  updateCreateTaskGroupId()
  // 获取任务列表
  fetchTasks({
    group_id: currentGroupId.value,
    status: filter.status,
    is_important: filter.isImportant,
    page: currentPage.value,
    page_size: pageSize.value
  })
})
</script>

<style scoped>
.home-page {
  max-width: 1200px;
  margin: 0 auto;
}
</style>
